import React, { useState, useEffect, useMemo, useRef } from 'react'
import { Button, Card, NavBar, List, Image, Input } from 'antd-mobile'
import { data, useNavigate, useSearchParams } from 'react-router-dom'
import { FilterOutline } from 'antd-mobile-icons'
// 调用防抖
import uselodash from '../../hook/uselodash'
import styles from './msg.module.css'

function Index() {
  let nav=useNavigate()
  let gao = useRef()
  let [xq] = useSearchParams()
  let tu = xq.get('img')
  let title = xq.get('title')
  let server_id = 5432
  let user_id = 1
  let [list, setlist] = useState([])
  const [value, setValue] = useState('')
  const socket = useMemo(() => {
    // Create WebSocket connection.
    return new WebSocket(`ws://124.221.74.149:8003/koa/ws?server_id=${server_id}&user_id=${user_id}`);
  }, [])

  useEffect(() => {
    // Connection opened
    socket.addEventListener("open", function (event) {
      socket.send(JSON.stringify({ type: 'getChatList' }));
    });

    // Listen for messages
    socket.addEventListener("message", function (event) {
      console.log("Message from server ", JSON.parse(event.data));
      let msg = JSON.parse(event.data)
      setlist(msg.data)
      console.log('55555')
    });
  }, [])

  // 点击发送
  let fa = (val) => {
      setValue(val)
    console.log('val',val)
    socket.send(JSON.stringify({
      type: 'addMessage',
      user_id,
      server_id,
      data: val
    }));
  }
  // gao.current.scrollTop=10000
  return (
    <div>
      <NavBar left={<div style={{ display: 'flex' }}>
        <Image style={{ width: '25px', height: '25px' }} src={tu}></Image>
        <span>{title}</span>
      </div>} right={<FilterOutline />} onBack={() => nav(-1)}></NavBar>

      {/* 聊天 */}

      <div className={styles.box}>
        <div className={styles.main} >
          <div className={styles.gun} ref={gao}>
            {
              list.length > 0 && list.map((item, index) => {
                return <div className={styles.list} key={index} >
                  <img className={styles.img} src={item.user_avatar} alt="" />
                  <div className={styles.zi}>
                    <p>{item.message}</p>
                  </div>
                </div>

              })
            }

          </div>

        </div>
        <div className={styles.footer}>
          <Input
            placeholder='请输入内容'
             value={value}
             onChange={val =>fa(val)}
          />
          <Button color='primary' fill='solid' onClick={() => fa()} >
            发送
          </Button>
        </div>
      </div>
    </div>
  )
}

export default Index
